﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;


namespace PhoenixCrabV6.Engine.IO
{
    public class DataContractManager<T>:IXmlManager<T>
    {
        public Type Type { get; set; }

        public DataContractManager()
        {
            Type = typeof(T);
        }

        public T Load(string path)
        {

            DataContractSerializer dcs = new DataContractSerializer(Type);
            FileStream fs = new FileStream(path, FileMode.Open);
            XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

            T xml = (T)dcs.ReadObject(reader);
            reader.Close();
            fs.Close();

            return xml;
        }

        public void Save(string path, T obj)
        {
            var dcs = new DataContractSerializer(Type);
            XmlWriterSettings settings = new XmlWriterSettings() {Indent = true};
            using (XmlWriter w = XmlWriter.Create(path, settings))
            {
                dcs.WriteObject(w,obj);
            }
        }
    }
}
